<?php

namespace app\common\model;

use addons\epay\library\Service;
use app\common\model\card\Dealer;
use Exception;
use fast\Random;
use think\Db;
use think\Model;


class Order extends Model
{


    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_data_text',
        'status_text'
    ];


    public function getTypeDataList()
    {
        return ['0' => __('Type_data 0'), '1' => __('Type_data 1'), '2' => __('Type_data 2')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }


    public function getTypeDataTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type_data']) ? $data['type_data'] : '');
        $list = $this->getTypeDataList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected static function init()
    {
        $time = "createtime<=UNIX_TIMESTAMP(DATE_SUB(NOW(),INTERVAL 10 MINUTE))";
        $order = Order::where($time)->where(["status" => '0'])->find();
        if (!empty($order)) {
            Order::where($time)->where(["status" => '0'])->update(["status" => '2']);
        }
    }

    public function member()
    {
        return $this->belongsTo('Member', 'member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 计算佣金
     * 店铺自建商品下单时计算佣金和商品结算
     * */
    public function calculateCommission($order)
    {
        $actual_payment = json_decode($order["commission"], true);
        if (in_array($order["type_data"], [0, 2])) {
            //普通商品和洗车卡
            //$regionservice = Regionservice::where(["region" => $actual_payment["address_all"]])->find();
            //2023-6-30 修改
            $regionservice = [];
            if (empty($order["commission"])) {
                $actual_payment["platform"] = 0;
            } else {
                $regionservice = Regionservice::where('FIND_IN_SET("' . $actual_payment["address_all"] . '", region)')
                    ->where(["status" => '1'])
                    ->find();
            }
            $regionservice_commission = 0;
            $merchant = Merchant::get($order["merchant_id"]);//门店
            $merchant_money = bcsub($actual_payment["price"], $actual_payment["platform"], 2);
            Db::startTrans();
            try {
                if ($merchant) {
                    //$merchant_money = $order["price"] - $order["platform_money"];//门店结算金额
                    $merchant_money = bcsub($actual_payment["price"], $actual_payment["platform"], 2);//门店结算金额
                    Regionservice::money($merchant_money, $merchant["id"], "订单（编号：" . $order["order_no"] . "，名称：" . $order["name"] . "）购买", 1);
                }
                if (!empty($regionservice)) {
                    //$regionservice_commission = floor(($actual_payment["platform"] * ($actual_payment["list"]["region_divide"] / 100)) * 100) / 100;//渠道分销商分佣
                    $regionservice_commission = $actual_payment["regionservice_commission"] ?? 0;//渠道分销商分佣
                    if ($regionservice_commission > 0) {
                        //修改订单中渠道分销商分佣字段
                        $order_update = [
                            "regionservice_commission" => $regionservice_commission,
                            "regionservice_id" => $regionservice["id"],
                        ];
                        Regionservice::money($regionservice_commission, $regionservice["id"], "订单（编号：" . $order["order_no"] . "，名称：" . $order["name"] . "）购买", 2);
                        \app\common\model\Message::create([
                            "title" => "店铺:" . $merchant["name"] ?? '' . "售出商品：" . $order["name"],
                            "member_ids" => $regionservice["id"],
                            "sende_data" => '4',
                            "info" => "店铺:" . $merchant["name"] ?? '' . "售出商品：" . $order["name"] . "(收益:" . $regionservice_commission . ")",
                            "createtime" => time(),
                        ]);
                    }
                }
                $order_update["merchantuser_money"] = $merchant_money;//商家金额
                $order->save($order_update);
                Db::commit();
                //你可以在此编写订单逻辑
            } catch (Exception $e) {
                Db::rollback();
            }
        }
        return true;
        return ["merchant_money" => $merchant_money, "merchant_id" => $merchant["id"], "momo" => "订单（编号：" . $order["order_no"] . "，名称：" . $order["name"] . "）购买"];
    }

    /**
     * 给购买卡包用户上级分钱
     * */
    public function agentCommission($order)
    {
        $agent_ratio = \think\Config::get('site.agent_ratio');
        $member = Member::get($order["member_id"]);
        if (!empty($member) && !empty($member["agent_id"])) {
            $agent_type = '4';
            if ($member["agent_data"] == 1) {
                //来源:0=自然流量,1=分销商,2=卡经销商
                $agent_member = Distributor::where(["id" => $member["agent_id"]])->find();
            }
            if ($member["agent_data"] == 2) {
                //来源:0=自然流量,1=分销商,2=卡经销商
                $agent_member = Dealer::where(["id" => $member["agent_id"]])->find();
                $agent_ratio = \think\Config::get('site.dealer_ratio');
                $agent_type = '3';
            }
            $agent_ratio = $agent_ratio ?? 5;
            if (!empty($agent_member)) {
                $money = bcmul($order["price"], ($agent_ratio / 100), 2);
                Db::startTrans();
                try {
                    $order->save([
                        "agent_id" => $agent_member["id"],
                        "agent_type" => $agent_type,
                        "agent_commission" => $money,
                    ]);
                    Regionservice::money($money, $agent_member["id"], "下级用户购买卡包（编号：" . $order["id"] . "，名称：" . $order["name"] . "）", $agent_type);
                    //发送消息
                    \app\common\model\Message::create([
                        "title" => "下级购买卡包",
                        "member_ids" => $agent_member["id"],
                        "sende_data" => $agent_type,
                        "info" => "下级用户购买卡包（编号：" . $order["id"] . "，名称：" . $order["name"] . "）",
                        "createtime" => time(),
                    ]);
                    Db::commit();
                    //你可以在此编写订单逻辑
                } catch (Exception $e) {
                    Db::rollback();
                }
            }
        }

    }

    /**
     * 核销时计算佣金和平台结算
     * */
    public function writeCalculateCommission($mycardlog, $washlog, $address, $merchant_id, $goods_price = 0)
    {
        if ($washlog["regionservice_commission"] <= 0) {
            //卡包
            $actual_payment = $this->actual_payment($goods_price, $address);
            if ($actual_payment) {
                $washlog_update = [
                    "platform_money" => $actual_payment["platform"],
                    "commission" => json_encode($actual_payment),
                ];
            }
            $merchant = Merchant::get($merchant_id);//门店
            if ($merchant) {
                //$merchant_money = $goods_price - $actual_payment["platform"];//门店结算金额
                if (!$actual_payment) $actual_payment["platform"] = 0;
                $merchant_money = bcsub($goods_price, $actual_payment["platform"], 2);//门店结算金额
                Regionservice::money($merchant_money, $merchant["id"], "核销记录（编号：" . $washlog["id"] . "，名称：" . $washlog["name"] . "）核销", 1);
                //发送消息
                \app\common\model\Message::create([
                    "title" => "核销成功",
                    "member_ids" => $merchant["id"],
                    "sende_data" => '1',
                    "info" => "核销记录（编号：" . $washlog["id"] . "，名称：" . $washlog["name"] . "）核销",
                    "createtime" => time(),
                ]);
                $washlog_update["merchantuser_money"] = $merchant_money;//商家金额
                $washlog->save($washlog_update);
            }
            /*if($actual_payment && isset($actual_payment["rules"]) && $actual_payment["id"]==1){
                $actual_payment["address_all"]=$address;
            }*/
            if ($actual_payment && !empty($actual_payment) && isset($actual_payment["address_all"])) {
                /*$regionservice = Regionservice::where(["region" => $actual_payment["address_all"]])->find();*/
                //2023-6-30 修改
                $regionservice = Regionservice::where('FIND_IN_SET("' . $actual_payment["address_all"] . '", region)')
                    ->where(["status" => '1'])
                    ->find();
                if (!empty($regionservice)) {
                    $washlog_update["regionservice_commission"] = $actual_payment["regionservice_commission"];
                    $washlog_update["regionservice_id"] = $regionservice["id"];
                    Regionservice::money($actual_payment["regionservice_commission"], $regionservice["id"], "核销记录（编号：" . $washlog["id"] . "，名称：" . $washlog["name"] . "）核销", 2);
                    //发送消息
                    \app\common\model\Message::create([
                        "title" => "店铺:" . $merchant["name"] ?? '' . "核销成功",
                        "member_ids" => $regionservice["id"],
                        "sende_data" => '4',
                        "info" => "核销记录（编号：" . $washlog["id"] . "，名称：" . $washlog["name"] . "）核销",
                        "createtime" => time(),
                    ]);
                    $washlog->save($washlog_update);
                }
            }
        } else {
            $merchant_money = $washlog["merchantuser_money"];
        }
        return $merchant_money;
    }

    /**
     * 计算平台抽佣 区域服务商分佣
     * */
    public function actual_payment($price, $address)
    {
        $actual_payment2 = $price;
        $actual_payment = 0;
        $platform = 0;
        $list = [];
        $address = explode("-", $address);
        if ($price > 1) {
            $list = Commissionrules::where('FIND_IN_SET("' . $address[0] . '", address) or FIND_IN_SET("' . $address[0] .
                $address[1] . '", address) or FIND_IN_SET("' . $address[0] . $address[1] . $address[2] . '", address)')
                ->find();
            //2023-9-4 lina 修改 start
            //if (empty($list)) return false;
            if (empty($list)){
                $list = Commissionrules::find(1);
            }
            //2023-9-4 lina 修改 end
            /*$platform=floor(($price*$list["merchant_smoke"]/100)*100)/100;//平台抽佣
            $platform=$platform<=0?0:$platform;
            $actual_payment=floor(($platform*$list["kabaw_divide_profit"]/100)*100)/100;//区域合伙人
            $actual_payment=$actual_payment<=0?0:$actual_payment;
            $actual_payment2=$price-$actual_payment<=0?0:$price-$actual_payment;*/
            bcscale(2);
            $platform = bcmul($price, ($list["merchant_smoke"] / 100));
            //$platform=floor(($price*$list["goods_smoke"]/100)*100)/100;//平台抽佣
            $platform = $platform <= 0 ? 0 : $platform;
            $actual_payment = bcmul($platform, ($list["kabaw_divide_profit"] / 100));
            //$actual_payment=floor(($platform*$list["favourable"]/100)*100)/100;//用户优惠金额
            $actual_payment = $actual_payment <= 0 ? 0 : $actual_payment;
            $actual_payment2 = bcsub($price, $actual_payment);
            $actual_payment2 = $actual_payment2 <= 0 ? 0 : $actual_payment2;
        }
        return ["price" => $price, "actual_payment" => $actual_payment2, "regionservice_commission" => $actual_payment, "platform" => $platform, "rules" => $list, "address" => $address[2], "address_all" => $address[0] . $address[1] . $address[2]];
    }


    /**
     * 普通商品核销码
     * */
    public function write_number($num = 6)
    {
        $write_number = Random::numeric($num);
        $log = $this->field("1")->where(["write_number" => $write_number, "status" => '3'])->find();
        if (!empty($log)) {
            $this->write_number($num);
        }
        return $write_number;
    }
}
